<template>
  <div class="multiple-identities-container">
    <el-card class="main-card">
      <template #header>
        <div class="card-header">
          <div class="title-wrapper">
            <el-icon class="header-icon"><Key /></el-icon>
            <h2 class="title">多身份管理</h2>
          </div>
        </div>
      </template>

      <!-- 步骤条 -->
      <el-steps
        :active="activeStep"
        finish-status="success"
        class="steps-nav"
        process-status="process"
        align-center
      >
        <el-step title="填写基本信息" description="输入原学号和姓名">
          <template #icon>
            <el-icon><User /></el-icon>
          </template>
        </el-step>
        <el-step title="选择目标身份" description="选择并填写目标身份信息">
          <template #icon>
            <el-icon><Key /></el-icon>
          </template>
        </el-step>
      </el-steps>

      <div class="form-container">
        <!-- 第一步：基本信息表单 -->
        <transition name="el-fade-in-linear">
          <el-form
            v-show="activeStep === 1"
            ref="formRef"
            :model="formData"
            :rules="formRules"
            label-width="140px"
            class="identity-form"
            :disabled="loading"
          >
            <!-- 学号输入框 -->
            <el-form-item label="学号" prop="henau_number">
              <el-input
                v-model="formData.henau_number"
                placeholder="请输入学号"
                clearable
                class="form-input"
              >
                <template #prefix>
                  <el-icon><User /></el-icon>
                </template>
              </el-input>
            </el-form-item>

            <!-- 姓名输入框 -->
            <el-form-item label="姓名" prop="name">
              <el-input
                v-model="formData.name"
                placeholder="请输入姓名"
                clearable
                class="form-input"
              >
                <template #prefix>
                  <el-icon><UserFilled /></el-icon>
                </template>
              </el-input>
            </el-form-item>

            <!-- 下一步按钮 -->
            <div class="form-footer">
              <el-button
                type="primary"
                :loading="loading"
                class="custom-button next-button"
                @click="handleNextStep"
              >
                下一步
                <el-icon class="next-icon"><ArrowRight /></el-icon>
              </el-button>
            </div>
          </el-form>
        </transition>

        <!-- 第二步：身份选择和信息填写 -->
        <div v-show="activeStep === 2">
          <!-- 身份选择器 -->
          <el-form
            ref="formRef2"
            :model="formData"
            :rules="formRules"
            label-width="140px"
            class="identity-form"
            :disabled="loading"
          >
            <el-form-item label="目标身份" prop="table_id">
              <el-select
                v-model="formData.table_id"
                placeholder="请选择身份"
                clearable
                class="form-input"
                @change="handleTableChange"
              >
                <template #prefix>
                  <el-icon><Key /></el-icon>
                </template>
                <el-option
                  v-for="table in tables"
                  :key="table.id"
                  :label="table.description"
                  :value="table.id"
                />
              </el-select>
            </el-form-item>
          </el-form>

          <!-- 字段填写表单 -->
          <template v-if="formData.table_id && fields.length > 0">
            <div class="divider">
              <el-divider content-position="left">
                <div class="divider-content">
                  <el-icon><Document /></el-icon>
                  <span>{{ getSelectedTableName }}信息</span>
                </div>
              </el-divider>
            </div>
            <el-form
              ref="fieldsFormRef"
              :model="formData"
              :rules="formRules"
              label-width="120px"
              class="fields-form"
              :disabled="loading"
            >
              <div class="form-grid">
                <el-form-item
                  v-for="field in fields"
                  :key="field.field_id"
                  :label="field.label + (field.must === '必须' ? ' *' : '')"
                  :prop="'data.' + field.field"
                  class="form-grid-item"
                >
                  <!-- 枚举类型字段 -->
                  <template v-if="field.type.startsWith('enum')">
                    <el-select
                      v-model="formData.data[field.field]"
                      :placeholder="'请选择' + field.label"
                      clearable
                      class="form-input"
                    >
                      <el-option
                        v-for="option in getEnumOptions(field.type)"
                        :key="option"
                        :label="option"
                        :value="option"
                      />
                    </el-select>
                  </template>
                  <!-- 普通输入字段 -->
                  <template v-else>
                    <el-input
                      v-model="formData.data[field.field]"
                      :placeholder="'请输入' + field.label"
                      clearable
                      class="form-input"
                    />
                  </template>
                </el-form-item>
              </div>
              <div class="form-footer">
                <el-button
                  :disabled="loading"
                  class="custom-button"
                  @click="handlePrevStep"
                >
                  <el-icon><ArrowLeft /></el-icon>
                  上一步
                </el-button>
                <el-button
                  type="primary"
                  :loading="loading"
                  class="custom-button"
                  @click="handleSubmit"
                >
                  <el-icon><Check /></el-icon>
                  提交
                </el-button>
              </div>
            </el-form>
          </template>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import {
  User,
  UserFilled,
  Key,
  Document,
  RefreshRight,
  Check,
  ArrowRight,
  ArrowLeft
} from "@element-plus/icons-vue";
import {
  getAllTable,
  getMultipleIdentityList,
  addMultipleIdentity,
  getPersonnelInfo
} from "@/api";

// 表格数据
const tables = ref([]);
const fields = ref([]);
const fieldsFormRef = ref<FormInstance>();

// 获取选中表格的名称
const getSelectedTableName = computed(() => {
  const selectedTable = tables.value.find(t => t.id === formData.table_id);
  return selectedTable?.description || "";
});

// 表单数据和规则
const formData = reactive({
  henau_number: "",
  name: "",
  table_id: null,
  data: {},
  originalInfo: {
    henau_number: "",
    name: ""
  }
});

// 表单验证规则
const formRules = reactive<FormRules>({
  henau_number: [
    { required: true, message: "请输入学号", trigger: "blur" },
    { min: 3, max: 20, message: "长度在 3 到 20 个字符", trigger: "blur" }
  ],
  name: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" }
  ],
  table_id: [{ required: true, message: "请选择身份", trigger: "change" }]
});

const formRef = ref<FormInstance>();
const loading = ref(false);
const activeStep = ref(1);

// 存储人员信息
const personnelInfo = ref(null);

// 获取所有身份表
const fetchTables = async () => {
  try {
    const res = await getAllTable();
    if (res.status === "success") {
      tables.value = res.data;
    }
  } catch (error) {
    console.error("获取身份表失败:", error);
    ElMessage.error("获取身份表失败");
  }
};

// 处理表格切换
const handleTableChange = async (tableId: number) => {
  if (!tableId) {
    fields.value = [];
    formData.data = {};
    return;
  }

  try {
    const res = await getMultipleIdentityList({ table_id: tableId });
    if (res.status === "success") {
      fields.value = res.data;
      // 初始化动态字段的数据和验证规则
      initFieldsData();
      // 填充人员信息
      if (personnelInfo.value) {
        handlePersonnelInfo();
      }
    }
  } catch (error) {
    console.error("获取字段失败:", error);
    ElMessage.error("获取字段失败");
  }
};

// 初始化动态字段的数据和验证规则
const initFieldsData = () => {
  // 重置数据
  formData.data = {
    soft_delete: 0
  };

  // 为所有字段添加验证规则
  fields.value.forEach(field => {
    formData.data[field.field] = "";
    if (field.must === "必须") {
      formRules["data." + field.field] = [
        {
          required: true,
          message:
            "请" +
            (field.type.startsWith("enum") ? "选择" : "输入") +
            field.label,
          trigger: field.type.startsWith("enum") ? "change" : "blur"
        }
      ];
    }
  });
};

// 获取枚举选项
const getEnumOptions = (type: string) => {
  try {
    const enumStr = type.substring(5, type.length - 1);
    return JSON.parse(`[${enumStr}]`);
  } catch (error) {
    console.error("解析枚举值失败:", error);
    return [];
  }
};

// 提交表单
const handleSubmit = async () => {
  if (!fieldsFormRef.value) return;
  console.log(formData);
  try {
    loading.value = true;
    await fieldsFormRef.value.validate();

    if (Object.keys(formData.data).length === 0) {
      ElMessage.warning("请先填写相关信息");
      return;
    }

    const res = await addMultipleIdentity({
      henau_number: formData.originalInfo.henau_number,
      name: formData.originalInfo.name,
      new_table_id: formData.table_id,
      data: formData.data
    });

    if (res.status === "success") {
      ElMessage.success("添加成功");
      resetForm();
    } else {
      ElMessage.error(res.message || "添加失败");
    }
  } catch (error) {
    console.error("提交失败:", error);
    ElMessage.error("提交失败");
  } finally {
    loading.value = false;
  }
};

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields();
  fieldsFormRef.value?.resetFields();
  fields.value = [];
  formData.data = {};
  formData.table_id = null;
  formData.originalInfo = {
    henau_number: "",
    name: ""
  };
  activeStep.value = 1; // 重置步骤到第一步
};

// 处理下一步
const handleNextStep = async () => {
  if (activeStep.value === 1) {
    try {
      await formRef.value?.validate();
      // 调用getPersonnelInfo接口验证人员信息
      const res = await getPersonnelInfo({
        henau_number: formData.henau_number,
        name: formData.name
      });

      if (res.status === "success") {
        // 保存原始信息
        formData.originalInfo.henau_number = formData.henau_number;
        formData.originalInfo.name = formData.name;
        // 保存人员信息用于后续填充
        personnelInfo.value = res.data;
        activeStep.value++;
      } else {
        ElMessage.warning("未找到该人员信息");
      }
    } catch (error) {
      console.error("验证失败:", error);
      ElMessage.warning("请先完成基本信息的填写");
    }
  }
};

// 处理上一步
const handlePrevStep = () => {
  if (activeStep.value > 1) {
    activeStep.value--;
  }
};

// 处理人员信息填充
const handlePersonnelInfo = () => {
  if (!personnelInfo.value || !fields.value.length) return;

  const info = personnelInfo.value;
  fields.value.forEach(field => {
    // 跳过学号字段，其他字段正常填充
    if (info[field.field] !== undefined && field.field !== "henau_number") {
      formData.data[field.field] = info[field.field];
    }
  });
};

// 页面加载时获取身份表
onMounted(fetchTables);
</script>

<style lang="scss" scoped>
// 添加动画关键帧
@keyframes fade-in-up {
  from {
    opacity: 0;
    transform: translateY(20px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes rotate-in {
  from {
    opacity: 0;
    transform: rotate(-180deg);
  }

  to {
    opacity: 1;
    transform: rotate(0);
  }
}

@keyframes fade-in {
  from {
    opacity: 0;
  }

  to {
    opacity: 1;
  }
}

.multiple-identities-container {
  min-height: calc(100vh - 120px);
  padding: 20px;
  animation: fade-in-up 0.6s ease-out;

  .main-card {
    max-width: 1000px;
    margin: 0 auto;
    overflow: hidden;
    background: linear-gradient(145deg, #fff 0%, #f8fbff 100%);
    border-radius: 16px;
    box-shadow: 0 8px 24px rgb(15 79 168 / 6%);
    transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);

    &:hover {
      box-shadow: 0 12px 32px rgb(15 79 168 / 10%);
      transform: translateY(-2px);
    }

    :deep(.el-card__body) {
      padding: 40px;
    }
  }

  .card-header {
    padding: 24px 32px;
    margin: -1px -1px 0;
    background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);

    .title-wrapper {
      display: flex;
      gap: 16px;
      align-items: center;

      .header-icon {
        font-size: 28px;
        color: #fff;
        animation: rotate-in 0.6s ease-out;
      }

      .title {
        margin: 0;
        font-size: 1.75rem;
        font-weight: 600;
        color: #fff;
        text-shadow: 0 2px 4px rgb(0 0 0 / 10%);
      }
    }
  }

  .form-container {
    padding: 20px 0;
  }

  .steps-nav {
    max-width: 800px;
    padding: 20px 0 40px;
    margin: 0 auto;

    :deep(.el-step__icon) {
      width: 40px;
      height: 40px;
      border: 2px solid #e6f0ff;
      box-shadow: 0 4px 12px rgb(24 144 255 / 10%);
      transition: all 0.3s ease;

      .el-step__icon-inner {
        font-size: 1.2rem;
        color: #1890ff;
      }
    }

    :deep(.el-step__title) {
      font-size: 1.1rem;
      font-weight: 500;
      color: #1890ff;
      transition: all 0.3s ease;
    }

    :deep(.el-step__description) {
      margin-top: 6px;
      font-size: 0.9rem;
      color: #8c8c8c;
    }

    :deep(.el-step.is-process) {
      .el-step__icon {
        background: #1890ff;
        border-color: #1890ff;
        transform: scale(1.1);

        .el-step__icon-inner {
          color: #fff;
        }
      }

      .el-step__title {
        color: #1890ff;
        transform: translateY(-2px);
      }
    }

    :deep(.el-step.is-finish) {
      .el-step__icon {
        color: #1890ff;
        background: #e6f7ff;
        border-color: #1890ff;
      }

      .el-step__title {
        color: #1890ff;
      }
    }

    :deep(.el-step__line) {
      background-image: linear-gradient(90deg, #e6f0ff 50%, transparent 50%);
      background-repeat: repeat-x;
      background-size: 8px 1px;
    }
  }

  .identity-form {
    max-width: 600px;
    padding: 40px;
    margin: 0 auto;
    background: #fff;
    border-radius: 16px;
    box-shadow: 0 4px 16px rgb(24 144 255 / 6%);
    transition: all 0.3s ease;

    &:hover {
      box-shadow: 0 6px 24px rgb(24 144 255 / 10%);
    }

    .form-input {
      width: 100%;

      :deep(.el-input__wrapper) {
        padding: 10px 16px;
        background: #f8fbff;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgb(24 144 255 / 6%);
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

        &:hover {
          box-shadow: 0 4px 12px rgb(24 144 255 / 10%);
          transform: translateY(-1px);
        }

        &.is-focus {
          background: #fff;
          box-shadow: 0 4px 16px rgb(24 144 255 / 15%);
        }

        .el-input__inner {
          font-size: 1rem;
          color: #262626;
        }
      }

      :deep(.el-input__prefix) {
        margin-right: 8px;

        .el-icon {
          font-size: 1.2rem;
          color: #1890ff;
        }
      }
    }

    :deep(.el-form-item__label) {
      padding-bottom: 8px;
      font-size: 1rem;
      font-weight: 500;
      color: #262626;
    }

    .form-footer {
      display: flex;
      justify-content: center;
      padding-top: 40px;
      margin-top: 32px;
      border-top: 1px dashed #e6f0ff;

      .custom-button {
        display: flex;
        gap: 8px;
        align-items: center;
        min-width: 160px;
        padding: 12px 32px;
        font-size: 1.1rem;
        font-weight: 500;
        color: #fff;
        background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
        border: none;
        border-radius: 10px;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

        &:not(:disabled):hover {
          box-shadow: 0 6px 16px rgb(24 144 255 / 25%);
          transform: translateY(-2px);
        }

        .el-icon {
          font-size: 1.3em;
          transition: transform 0.3s ease;
        }

        &:hover .el-icon {
          transform: translateX(4px);
        }
      }
    }
  }

  .fields-form {
    padding: 40px;
    margin-top: 32px;
    background: #fff;
    border-radius: 16px;
    box-shadow: 0 4px 16px rgb(24 144 255 / 6%);
    transition: all 0.3s ease;

    &:hover {
      box-shadow: 0 6px 24px rgb(24 144 255 / 10%);
    }

    .form-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
      gap: 28px;
      animation: fade-in 0.4s ease-out;
    }

    .form-grid-item {
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-1px);
      }
    }

    .form-footer {
      display: flex;
      gap: 20px;
      justify-content: center;
      padding-top: 40px;
      margin-top: 40px;
      border-top: 1px dashed #e6f0ff;

      .custom-button {
        display: flex;
        gap: 10px;
        align-items: center;
        justify-content: center;
        min-width: 140px;
        padding: 12px 32px;
        font-size: 1.1rem;
        font-weight: 500;
        color: #fff;
        background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
        border: none;
        border-radius: 10px;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

        &:not(:disabled):hover {
          box-shadow: 0 6px 16px rgb(24 144 255 / 25%);
          transform: translateY(-2px);
        }

        &:not(:disabled):active {
          transform: translateY(1px);
        }

        .el-icon {
          font-size: 1.3em;
          transition: transform 0.3s ease;
        }

        &:hover .el-icon {
          &[class*="arrow-left"] {
            transform: translateX(-4px);
          }

          &[class*="arrow-right"],
          &[class*="check"] {
            transform: translateX(4px);
          }
        }

        &[type="default"] {
          color: #1890ff;
          background: #fff;
          border: 1px solid #1890ff;

          &:not(:disabled):hover {
            color: #fff;
            background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
          }
        }
      }
    }
  }

  .divider {
    margin: 40px 0;
    opacity: 0.8;

    :deep(.el-divider__text) {
      padding: 0 24px;
      background: transparent;
    }

    .divider-content {
      display: flex;
      gap: 12px;
      align-items: center;
      padding: 8px 16px;
      font-size: 1.2rem;
      font-weight: 500;
      color: #1890ff;
      background: #e6f7ff;
      border-radius: 20px;
      box-shadow: 0 2px 8px rgb(24 144 255 / 15%);

      .el-icon {
        font-size: 1.3em;
      }
    }
  }
}

// 暗色主题适配
:root[class*="dark"] {
  .multiple-identities-container {
    background-color: #141414;

    .main-card {
      background: linear-gradient(145deg, #1f1f1f 0%, #141414 100%);
      box-shadow: 0 8px 24px rgb(0 0 0 / 20%);
    }

    .card-header {
      background: linear-gradient(135deg, #096dd9 0%, #003a8c 100%);
    }

    .identity-form,
    .fields-form {
      background: #1f1f1f;
      box-shadow: 0 4px 16px rgb(0 0 0 / 20%);

      .form-input {
        :deep(.el-input__wrapper) {
          background: #141414;
          box-shadow: 0 2px 8px rgb(0 0 0 / 20%);

          &.is-focus {
            background: #1f1f1f;
            box-shadow: 0 4px 16px rgb(24 144 255 / 10%);
          }
        }
      }
    }

    .divider-content {
      background: #111d2c;
      box-shadow: 0 2px 8px rgb(0 0 0 / 20%);
    }
  }
}
</style>
